package com.woniuxy.mini;

import com.woniuxy.core.service.AllArticleService;
import com.woniuxy.core.service.RelArticleTypeService;
import com.woniuxy.entity.AllArticle;
import com.woniuxy.entity.AllUser;
import com.woniuxy.feign.AllUserAPI;
import com.woniuxy.feign.UserStatsFeignClient;
import com.woniuxy.util.ResponseData;
import com.woniuxy.enums.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author hq
 * @Date 2025/7/10$ 12:06$
 * @Description TODO
 * @Params $
 * @Return $
 **/

@RestController
@RequestMapping("/articles")
@Slf4j
public class ArticleController {

    @Autowired
    private AllArticleService allArticleService;
    @Autowired
    private AllUserAPI allUserAPI; // 注入 Feign 客户端

    @Autowired
    private RelArticleTypeService relArticleTypeService;

    @Autowired
    private UserStatsFeignClient userStatsFeignClient;

    // 新增帖子
    @PostMapping("/add")
    public ResponseData<Boolean> createArticle(@RequestBody AllArticle article) {
        boolean saved = allArticleService.save(article);

        if (saved) {
            // 更新用户帖子数
            if (article.getUserId() != null) {
                ResponseData<Void> response = userStatsFeignClient.incrementPostCount(article.getUserId());
                if (response.getCode() != 200) {
                    log.error("用户帖子数增加失败，用户ID：{}", article.getUserId());
                }
            }
            // 关联标签
            if (article.getTypeIds() != null && !article.getTypeIds().isEmpty()) {
                relArticleTypeService.addRelations(article.getId(), article.getTypeIds());
            }
        }

        return saved ? ResponseData.ok(true) : ResponseData.fail(ResponseEnum.FAIL);
    }

    // 查询所有帖子并附加用户信息，根据浏览量从高到低输出
    @GetMapping("all")
    public ResponseData<List<AllArticle>> getAllArticles() {
        List<AllArticle> articles = allArticleService.getAllArticlesByViewCount();
        if (articles.isEmpty()) {
            return ResponseData.ok(articles);
        }
        // 获取所有用户信息
        ResponseData<List<AllUser>> usersResponse = allUserAPI.getAllUsers();
        if (usersResponse.getCode() != 200 || usersResponse.getData() == null) {
            return ResponseData.ok(articles); // 用户信息获取失败，仅返回文章
        }
        // 构建用户ID -> 用户对象的映射表
        Map<Long, AllUser> userMap = usersResponse.getData().stream()
                .collect(Collectors.toMap(AllUser::getUserId, user -> user));
        // 填充用户信息到文章中
        for (AllArticle article : articles) {
            if (article.getUserId() != null) {
                article.setUser(userMap.get(article.getUserId()));
            }
        }
        return ResponseData.ok(articles);
    }


    // 根据 ID 查询单个帖子，同时增加浏览量
    @GetMapping("/{id}")
    public ResponseData<AllArticle> getArticleById(@PathVariable("id") Long id) {
        allArticleService.incrementViewCount(id);
        AllArticle article = allArticleService.getArticleWithLikeCountById(id);
        if (article != null) {
            if (article.getUserId() != null) {
                ResponseData<AllUser> result = allUserAPI.getUserById(article.getUserId());
                if (result.getCode() == 200 && result.getData() != null) {
                    article.setUser(result.getData());
                }
            }
        }
        return article != null ? ResponseData.ok(article) : ResponseData.fail(ResponseEnum.FAIL);
    }


    // 更新帖子
    @PutMapping("/{id}")
    public ResponseData<Boolean> updateArticle(@PathVariable("id") Long id, @RequestBody AllArticle article) {
        article.setId(id);
//        设置当前时间为帖子更新时间
        article.setUpdateTime(java.time.LocalDateTime.now());
        boolean updated = allArticleService.updateById(article);
        return updated ? ResponseData.ok(true) : ResponseData.fail(ResponseEnum.FAIL);
    }

    // 删除帖子
    @DeleteMapping("/{id}")
    public ResponseData<Boolean> deleteArticle(@PathVariable("id") Long id) {
        AllArticle article = allArticleService.getById(id);
        if (article == null) {
            return ResponseData.fail(ResponseEnum.FAIL);
        }

        boolean removed = allArticleService.removeById(id);

        if (removed) {
            // 更新用户帖子数
            if (article.getUserId() != null) {
                ResponseData<Void> response = userStatsFeignClient.decrementPostCount(article.getUserId());
                if (response.getCode() != 200) {
                    log.error("用户帖子数减少失败，用户ID：{}", article.getUserId());
                }
            }
        }

        return removed ? ResponseData.ok(true) : ResponseData.fail(ResponseEnum.FAIL);
    }

    @GetMapping("/search")
    public ResponseData<List<AllArticle>> searchArticlesByTitle(@RequestParam("title") String title) {
        List<AllArticle> articles = allArticleService.searchArticlesByTitle(title);
        return !articles.isEmpty() ? ResponseData.ok(articles) : ResponseData.fail(ResponseEnum.FAIL);
    }

    /**
     * 根据帖子ID查询帖子的发布者ID
     *
     * @param articleId 帖子ID
     * @return 发布者ID
     */
    @GetMapping("/getAuthorId/{articleId}")
    public Long getAuthorIdByArticleId(@PathVariable("articleId") Long articleId) {
        return allArticleService.getAuthorIdByArticleId(articleId);
    }
    /**
     * 根据用户ID查询该用户的所有帖子
     * @param userId 用户ID
     * @return 响应数据（帖子列表）
     */
    @GetMapping("/user/{userId}")
    public ResponseData<List<AllArticle>> getArticlesByUserId(@PathVariable("userId") Long userId) {
        List<AllArticle> articles = allArticleService.getArticlesByUserId(userId);
        return ResponseData.ok(articles);
    }

}